<?php
namespace App\Models\ApiDoc;

use App\Facades\ScarecrowAuth;
use Illuminate\Support\Facades\DB;

class ApiDocModel {

	/**
	 * 创建API
	 * @param $allData
	 * @return array
	 */
	public function createApi($allData) {
		$projectId = $allData['projectId'];
		if (!ScarecrowAuth::hasAuthEditProject($projectId, APP_USER_TOKEN)) {
			return ModelReturn(1, '无权限添加接口');
		}

		$projectObj = DB::table('sc_api_doc_project')->where(['id'=>$allData['projectId'], 'state'=>1])->first();
		if (!$projectObj) {
			return ModelReturn(2, '项目不存在,或被停用');
		}

		$categoryObj = DB::table('sc_api_doc_category')->where(['id'=>$allData['categoryId'], 'project_id'=>$allData['projectId'], 'state'=>1])->first();
		if (!$categoryObj) {
			return ModelReturn(3, '分类不存在');
		}

		$paramArr = [];
		$paramList = ($allData['paramList'] ?? '');
		if ($paramList) {
			$paramList = json_decode($paramList, true);
		}

		foreach ($paramList as $item) {
			$paramArr[] = [
				'title' => $item['paramName'],
				'type' => $item['paramType'],
				'must' => $item['paramMust'],
				'desc' => $item['paramDesc'],
			];
		}

		$createTime = time();
		$insertData = [
			'title'	=>	$allData['title'],
			'url'	=>	$allData['url'],
			'request_method'	=>	$allData['requestMethod'],
			'status'	=>	1,
			'create_time'	=>	$createTime,
			'update_time'	=>	$createTime,
			'param'			=>	json_encode($paramArr),
			'result'		=>	$allData['result'],
			'category_id'	=>	$allData['categoryId'],
			'project_id'	=>	$allData['projectId']
		];
		$iCnt = DB::table('sc_api_doc')->insertGetId($insertData);
		if ($iCnt) {
			$allData['id'] = $iCnt;
			HandleLog()->addLog('i', $allData, '创建了接口');
			return ModelReturn(0, '创建成功');
		} else {
			return ModelReturn(4, '创建失败,请稍后再试');
		}
	}

	/**
	 * 编辑API
	 * @param $allData
	 * @return array
	 */
	public function editApi($allData) {
		$projectId = $allData['projectId'];
		if (!ScarecrowAuth::hasAuthEditProject($projectId, APP_USER_TOKEN)) {
			return ModelReturn(1, '无权限编辑接口');
		}

		$projectObj = DB::table('sc_api_doc_project')->where(['id'=>$allData['projectId'], 'state'=>1])->first();
		if (!$projectObj) {
			return ModelReturn(2, '项目不存在');
		}

		$categoryObj = DB::table('sc_api_doc_category')->where(['id'=>$allData['categoryId'], 'project_id'=>$allData['projectId'], 'state'=>1])->first();
		if (!$categoryObj) {
			return ModelReturn(3, '分类不存在');
		}

		$apiObj = DB::table('sc_api_doc')->where(['id'=>$allData['apiId'], 'project_id'=>$allData['projectId'],'status'=>1])->first();
		if (!$apiObj) {
			return ModelReturn(4, '接口不存在');
		}

		$paramArr = [];
		$paramList = ($allData['paramList'] ?? '');
		if ($paramList) {
			$paramList = json_decode($paramList, true);
		}
		foreach ($paramList as $item) {
			$paramArr[] = [
				'title' => $item['paramName'],
				'type' => $item['paramType'],
				'must' => $item['paramMust'],
				'desc' => $item['paramDesc'],
			];
		}


		$createTime = time();
		$updateData = [
			'title'	=>	$allData['title'],
			'url'	=>	$allData['url'],
			'request_method'	=>	$allData['requestMethod'],
			'update_time'	=>	$createTime,
			'param'			=>	json_encode($paramArr),
			'result'		=>	$allData['result'],
			'category_id'	=>	$allData['categoryId']
		];
		$iCnt = DB::table('sc_api_doc')->where('id', $allData['apiId'])->update($updateData);
		if ($iCnt) {
			HandleLog()->addLog('u', $allData, '编辑了接口');
			return ModelReturn(0, '修改成功');
		} else {
			return ModelReturn(5, '修改失败,请稍后再试');
		}
	}

	/**
	 * 获取接口文档分页
	 * @param $allData
	 * @return array
	 */
	public function getApiDocListPage($allData) {
		if (!ScarecrowAuth::hasAuthEditProject($allData['projectId'], APP_USER_TOKEN)) {
			return ModelReturn(1, '无权限获取当前列表');
		}

		$index = ($allData['page'] - 1) * $allData['limit'];
		$total = DB::table('sc_api_doc')->where(['category_id'=>$allData['categoryId'], 'project_id'=>$allData['projectId'], 'status'=>1])->count('id');
		$allApiList = DB::table('sc_api_doc')->where(['category_id'=>$allData['categoryId'], 'project_id'=>$allData['projectId'], 'status'=>1])->offset($index)->limit($allData['limit'])->orderByDesc('id')->get();
		$allApiList = DbObjectToArr($allApiList);
		$relData = [
			'total'	=>	$total,
			'limit'	=>	$allData['limit'],
			'page'	=>	$allData['page'],
			'list'	=>	$allApiList
		];

		return ModelReturn(0, '获取成功', $relData);
	}

	/**
	 * 获取当前用户能查看的接口列表
	 * @param $allData
	 * @return array
	 */
	public function getApiDocList($allData) {
		$apiName = addslashes($allData['apiName'] ?? "");
		$userId = ScarecrowAuth::id(APP_USER_TOKEN);
		$isProjectManage = DB::table('sc_user_project_auth')->where(['user_id'=>$userId, 'project_id'=>$allData['projectId']])->first();
		$isAllProjectManage = DB::table('sc_user_all_project_auth')->where(['user_id'=>$userId])->first();
		if (ScarecrowAuth::hasAuthEditProject($allData['projectId'], APP_USER_TOKEN) || $isProjectManage || $isAllProjectManage) {
			$allApiListObj = DB::table('sc_api_doc as t1')->leftJoin('sc_api_doc_category as t2', 't1.category_id','=','t2.id')->where(['t1.project_id'=>$allData['projectId'], 't1.status'=>1]);
			if ($allData['categoryId'] > 0) {
				$allApiListObj->where('t1.category_id', $allData['categoryId']);
			}

			if ($apiName) {
				$allApiListObj->whereRaw("(t1.title like '%{$apiName}%' OR t1.url like '%{$apiName}%')");
			}

			$allApiList = $allApiListObj->orderByDesc('t1.id')->select(["t1.*", "t2.name as categoryName"])->get();
		} else {
			$allApiListObj = DB::table('sc_api_doc as t1')->leftJoin('sc_user_read_api_doc as t2', 't1.id','=','t2.api_doc_id')->leftJoin('sc_api_doc_category as t3', 't3.id', '=', 't1.category_id')->where(['t1.project_id'=>$allData['projectId'], 't1.status'=>1, 't2.user_id'=>$userId]);

			if ($allData['categoryId'] > 0) {
				$allApiListObj->where(['t1.category_id'=>$allData['categoryId']]);
			}

			if ($apiName) {
				$allApiListObj->whereRaw("t1.title like '%{$apiName}%'");
			}

			$allApiList = $allApiListObj->orderByDesc('t1.id')->select(["t1.*", "t3.name as categoryName"])->get();
		}
		$allApiList = DbObjectToArr($allApiList);
		array_walk($allApiList, function (&$item){
			$item['update_time'] = date("Y-m-d H:i:s", $item['update_time']);
			$item['request_method'] = strtoupper($item['request_method']);
		});
		return ModelReturn(0, '获取成功', $allApiList);
	}

	/**
	 * 获取接口文档详情
	 * @param $apiId
	 * @return array
	 */
	public function getApiDocInfo($apiId){
		if (!ScarecrowAuth::hasAuthViewProject($apiId, APP_USER_TOKEN)) {
			return ModelReturn(1, '无权限查看当前接口信息');
		}

		$apiDocInfo = DB::table('sc_api_doc as t1')->leftJoin('sc_api_doc_project as t2', 't2.id','=','t1.project_id')->leftJoin('sc_api_doc_category as t3', 't3.id','=','t1.category_id')->where(['t1.id'=>$apiId, 't1.status'=>1, 't2.state'=>1, 't3.state'=>1])->select(['t1.*','t2.name as projectName', 't3.name as categoryName'])->first();
		$apiDocInfo = DbObjectToArr($apiDocInfo);
		return ModelReturn(0, '获取成功', $apiDocInfo);
	}

	/**
	 * 删除接口
	 * @param $apiId
	 * @return array
	 */
	public function deleteApi($apiId) {
		$apiObj = DB::table('sc_api_doc')->where(['id'=>$apiId, 'status'=>1])->first();
		if (!$apiObj) {
			return ModelReturn(1, '接口不存在');
		}

		if (!ScarecrowAuth::isAdmin(APP_USER_TOKEN) && !ScarecrowAuth::hasAuthEditProject($apiObj->project_id, APP_USER_TOKEN)) {
			return ModelReturn(2, '无权限对该接口进行删除');
		}

		DB::table('sc_api_doc')->where(['id'=>$apiId])->update([
			'status'	=>	9,
			'update_time'	=>	time()
		]);
		HandleLog()->addLog('i', ['apiId'=>$apiId], '删除了接口');
		return ModelReturn(0, '删除成功');
	}

	/**
	 * 获取某个项目的所有接口导出数据
	 * @param $projectId
	 * @return array
	 */
	public function exportProjectApiList($projectId) {
		$projectObj = DB::table('sc_api_doc_project')->where(['id'=>$projectId, 'state'=>1])->first();
		if (!$projectObj) {
			return ModelReturn(1, '项目被停用或不存在，不允许下载');
		}
		$projectName = $projectObj->name;
		$userId = ScarecrowAuth::id(APP_USER_TOKEN);
		$isProjectManage = DB::table('sc_user_project_auth')->where(['user_id'=>$userId, 'project_id'=>$projectId])->first();
		$isAllProjectManage = DB::table('sc_user_all_project_auth')->where(['user_id'=>$userId])->first();
		if (ScarecrowAuth::hasAuthEditProject($projectId, APP_USER_TOKEN) || $isProjectManage || $isAllProjectManage) {
			$allApiList = DB::table('sc_api_doc as t1')->leftJoin('sc_api_doc_category as t2', 't1.category_id','=','t2.id')->where(['t1.project_id'=>$projectId, 't1.status'=>1])->orderByDesc('t1.id')->select(["t1.*", "t2.name as categoryName"])->get();
		} else {
			$allApiList = DB::table('sc_api_doc as t1')->leftJoin('sc_user_read_api_doc as t2', 't1.id','=','t2.api_doc_id')->leftJoin('sc_api_doc_category as t3', 't3.id', '=', 't1.category_id')->where(['t1.project_id'=>$projectId, 't1.status'=>1, 't2.user_id'=>$userId])->orderByDesc('t1.id')->select(["t1.*", "t3.name as categoryName"])->get();
		}
		$allApiList = DbObjectToArr($allApiList);
		array_walk($allApiList, function (&$item){
			$item['request_method'] = strtoupper($item['request_method']);
		});


		$relData = [
			'projectName'	=>	$projectName,
			'categoryList'	=>	[]
		];

		$categoryList = [];
		foreach ($allApiList as $api) {
			if (!array_key_exists($api['categoryName'], $categoryList)) {
				$categoryList[$api['categoryName']] = [
					'categoryName'	=>	$api['categoryName'],
					'apiList'		=>	[]
				];
			}
			$api['result'] = DataToHtmlShow($api['result']);
			$api['paramArr'] = json_decode($api['param'], true);
			if (!$api['paramArr']) {
				$api['paramArr'] = [];
			}
			$categoryList[$api['categoryName']]['apiList'][] = $api;
		}
		$relData['categoryList'] = $categoryList;
		return ModelReturn(0, '获取成功', $relData);
	}
}